<template>
  <div class="app-container">
    <el-form ref="queryForm" :model="queryParams" :inline="true">
      <el-form-item label="菜单名称" prop="menuName">
        <el-input
          v-model="queryParams.menuName"
          size="small"
          style="width: 240px"
          clearable
          placeholder="请输入菜单名称"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="getData"
        >
          搜索
        </el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">
          重置
        </el-button>
      </el-form-item>
    </el-form>
    <div class="filter-container">
      <el-row :gutter="10">
        <el-col :span="1.5">
          <el-button
            type="primary"
            size="mini"
            plain
            icon="el-icon-plus"
            @click="handleAdd()"
          >
            新增
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="info"
            size="mini"
            plain
            icon="el-icon-sort"
            @click="toggleExpand"
          >
            展开/折叠
          </el-button>
        </el-col>
        <right-toolbar @queryTable="getData"></right-toolbar>
      </el-row>
    </div>
    <el-table
      :data="menuData"
      style="width: 100%"
      v-loading="loading"
      v-if="showTable"
      row-key="navId"
      :default-expand-all="isExpandAll"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
    >
      <el-table-column
        prop="item"
        label="菜单名称"
        show-overflow-tooltip
        width="160"
        fixed
      ></el-table-column>
      <el-table-column prop="icon" label="图标" align="center" width="100">
        <template slot-scope="scope">
          <i
            :class="scope.row.icon"
            v-if="scope.row.icon.includes('el-icon')"
          />
          <svg-icon v-else :icon-class="scope.row.icon" />
        </template>
      </el-table-column>
      <el-table-column prop="sort" label="排序" width="60"></el-table-column>
      <el-table-column
        prop="url"
        label="权限标识"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column
        prop="component"
        label="组件路径"
        show-overflow-tooltip
        width="200"
      ></el-table-column>
      <el-table-column
        prop="instruction"
        label="描述"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column
        prop="createdTime"
        label="创建时间"
        align="center"
        width="160"
      ></el-table-column>
      <el-table-column label="操作" fixed="right" width="200">
        <template slot-scope="scope">
          <el-button
            type="text"
            size="mini"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row.navId)"
          >
            修改
          </el-button>
          <el-button
            type="text"
            size="mini"
            icon="el-icon-plus"
            v-if="scope.row.parentId == 0"
            @click="handleAdd(scope.row.navId)"
          >
            新增
          </el-button>
          <el-button
            size="text"
            type="danger"
            icon="el-icon-delete"
            @click="handleDelete(scope.row.navId)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 新增或修改对话框 -->
    <el-dialog :title="title" :visible.sync="open" append-to-body width="680px">
      <el-form ref="form" :model="form" label-width="100px" :rules="rules">
        <el-row>
          <el-col :span="24">
            <el-form-item label="上级菜单">
              <treeselect
                v-model="form.parentId"
                :options="menuOptions"
                :normalizer="normalizer"
                :show-count="true"
                :default-expand-level="1"
                placeholder="选择上级菜单"
                @select="selectParent"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="菜单图标" prop="icon">
              <el-popover
                placement="bottom-start"
                width="500"
                trigger="click"
                @show="$refs['iconSelect'].reset()"
              >
                <IconSelect ref="iconSelect" @selected="selected" />
                <el-input
                  class="iconInput"
                  slot="reference"
                  v-model="form.icon"
                  placeholder="点击选择图标"
                  readonly
                >
                  <svg-icon
                    v-if="form.icon && !form.icon.includes('el-icon')"
                    slot="prefix"
                    :icon-class="form.icon"
                    class="el-input__icon"
                    style="height: 32px; width: 16px"
                  />
                  <i
                    v-else-if="form.icon && form.icon.includes('el-icon')"
                    slot="prefix"
                    class="el-input__icon"
                    :class="form.icon"
                  />
                  <i
                    v-else
                    slot="prefix"
                    class="el-icon-search el-input__icon"
                  />
                </el-input>
              </el-popover>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="菜单名称" prop="item">
              <el-input
                v-model="form.item"
                placeholder="请输入菜单名称"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="显示排序" prop="sort">
              <el-input-number
                v-model="form.sort"
                controls-position="right"
                :min="1"
              ></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="form.parentId == 0 ? 24 : 12">
            <el-form-item prop="path">
              <span slot="label">
                <el-tooltip
                  content="访问的路由地址，如：`user`"
                  placement="top"
                >
                  <i class="el-icon-question"></i>
                </el-tooltip>
                路由地址
              </span>
              <el-input v-model="form.path" placeholder="请输入路由地址" />
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="form.parentId != 0">
            <el-form-item prop="component">
              <span slot="label">
                <el-tooltip
                  content="访问的组件路径，如：`portal/mySalary/index`，默认在`views`目录下"
                  placement="top"
                >
                  <i class="el-icon-question"></i>
                </el-tooltip>
                组件路径
              </span>
              <el-input v-model="form.component" placeholder="请输入组件路径" />
            </el-form-item>
          </el-col>
          <el-col :span="24" v-if="form.parentId != 0">
            <el-form-item prop="url">
              <span slot="label">
                <el-tooltip
                  content="访问的页面的权限标识，如：`/salary/my/**`"
                  placement="top"
                >
                  <i class="el-icon-question"></i>
                </el-tooltip>
                权限标识
              </span>
              <el-input v-model="form.url" placeholder="请输入权限标识" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="菜单描述" prop="instruction">
              <el-input
                type="textarea"
                :rows="2"
                v-model="form.instruction"
                placeholder="请输入菜单描述"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer">
        <el-button type="primary" @click="submitForm" :disabled="buttonState.submitDisabled">
          确 定
        </el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import IconSelect from '@/components/IconSelect'
export default {
  name: 'PageSetting',
  components: { Treeselect, IconSelect },
  data() {
    return {
      menuData: null,
      buttonState: {
        submitDisabled: false
      },
      ids: [],
      queryParams: {
        menuName: undefined,
      },
      form: {},
      open: false,
      title: undefined,
      loading: false,
      // 是否展开，默认全部折叠
      isExpandAll: false,
      showTable: true,
      title: '',
      open: false,
      menuOptions: [],
      rules: {
        icon: [{ required: true, message: '请选择菜单图标', trigger: 'blur' }],
        item: [{ required: true, message: '请输入菜单名称', trigger: 'blur' }],
        sort: [{ required: true, message: '请输入显示排序', trigger: 'blur' }],
        path: [{ required: true, message: '请输入路由地址', trigger: 'blur' }],
        component: [
          { required: true, message: '请输入组件路径', trigger: 'blur' },
        ],
        url: [{ required: true, message: '请输入权限标识', trigger: 'blur' }],
      },
    }
  },
  created() {
    this.getData()
  },
  methods: {
    // 选中上级菜单
    selectParent() {
      this.$nextTick(() => {
        this.getSort()
      })
    },
    // 选择图标
    selected(name) {
      this.form.icon = name
    },
    resetQuery() {
      this.resetForm('queryForm')
      this.getData()
    },
    submitForm() {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.buttonState.submitDisabled = true;
          if (!this.form.navId) {
            // 新增
            this.postRequest('/manage/page/', this.form).then(resp => {
              this.open = false;
              this.buttonState.submitDisabled = false;
              this.getData();
            }).catch(() => {
              this.buttonState.submitDisabled = false;
            });
          } else {
            // 修改
            this.putRequest('/manage/page/', this.form).then(resp => {
              this.open = false;
              this.buttonState.submitDisabled = false;
              this.getData();
            }).catch(() => {
              this.buttonState.submitDisabled = false;
            });
          }
        }
      });
    },
    handleDelete(navId) {
      this.$confirm('此操作将永久删除菜单是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.deleteRequest(`/manage/page/${navId}`).then(() => {
          this.getData()
        })
      }).catch(() => {});
    },
    handleUpdate(navId) {
      this.getRequest(`/manage/page/${navId}`).then((resp) => {
        if (resp) {
          this.reset()
          this.getParentList()
          this.form = resp.data
          this.title = '修改菜单'
          this.open = true
        }
      })
    },
    handleAdd(navId) {
      this.reset()
      if (navId) {
        this.form.parentId = navId
      } else {
        this.form.parentId = 0
      }
      this.getParentList()
      this.getSort()
      this.title = '新增菜单'
      this.open = true
    },
    cancel() {
      this.open = false
      setTimeout(() => {
        this.reset()
      }, 200)
    },
    reset() {
      this.form = {
        navId: undefined,
        parentId: 0,
        item: undefined,
        icon: undefined,
        sort: undefined,
      }
      this.resetForm('form')
    },
    // 展开/折叠操作
    toggleExpand() {
      this.showTable = false
      this.isExpandAll = !this.isExpandAll
      this.$nextTick(() => {
        this.showTable = true
      })
    },
    // 获取菜单排序
    getSort() {
      this.getRequest(`/manage/page/getSort/${this.form.parentId}`).then(
        (resp) => {
          if (resp) {
            this.form.sort = resp.data
          }
        }
      )
    },
    // 获取上级菜单
    getParentList() {
      this.getRequest('/manage/page/pList').then((resp) => {
        if (resp) {
          this.menuOptions = []
          const menu = { navId: 0, item: '主类目', children: [] }
          menu.children = resp.data
          this.menuOptions.push(menu)
        }
      })
    },
    /** 转换菜单数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children
      }
      return {
        id: node.navId,
        label: node.item,
        children: node.children,
      }
    },
    getData() {
      this.loading = true
      this.showTable = false
      this.getRequest('/manage/page/', this.queryParams).then((resp) => {
        if (resp) {
          this.menuData = resp.data
          this.showTable = true
          this.loading = false
        }
      })
    },
  },
}
</script>

<style lang="scss" scoped>
.app-container {
  .filter-container {
    padding-top: 0;
  }
}
</style>
<style lang="scss">
.vue-treeselect__input-container {
  input {
    height: 36px !important;
  }
}

.iconInput {
  input {
    cursor: pointer !important;
  }
}
</style>
